package com.aiju.cash.ui.good.fragment;

import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.aiju.base.fragment.BaseLazyFragment;
import com.aiju.bean.Good;
import com.aiju.bean.GoodsType;
import com.aiju.cash.R;
import com.aiju.cash.core.api.DataJson;
import com.aiju.cash.core.api.GoodApi;
import com.aiju.cash.ui.good.GoodAddActivity;
import com.aiju.cash.ui.good.adapter.CategoryAdapter;
import com.aiju.cash.ui.good.adapter.TeamsAndHeaderAdapter;
import com.aiju.cash.ui.good.manager.GoodManager;
import com.aiju.support.recyclerView.DividerItemDecoration;
import com.aiju.utils.T;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.timehop.stickyheadersrecyclerview.StickyRecyclerHeadersDecoration;
import com.zhy.http.okhttp.callback.StringCallback;

import java.util.List;

import okhttp3.Call;

/**
 * @author: 佐为
 * @date: 2016-12-12 16:41
 * @version: V1.0
 * @Description: 描述
 */
public class GoodFragment extends BaseLazyFragment implements CategoryAdapter.OnItemClickListener {

    private RecyclerView recyclerviewCategory;
    private RecyclerView recyclerviewTeams;

    private LinearLayoutManager mTeamsLayoutManager;
    private LinearLayoutManager mCategoryLayoutManager;


    private CategoryAdapter categoryAdapter;
    private TeamsAndHeaderAdapter teamsAndHeaderAdapter;

    private int show;
    private int oldSelectedPosition = 0;
    public static final int DELETE = 0;
    public static final int SHOP = 1;

    private GoodManager goodManager;

    public void setOnData(OnData mOnData) {
        this.mOnData = mOnData;
    }

    private OnData mOnData;

    public interface OnData {
        void onData();
    }

    @Override
    protected void lazyLoad() {
        if (recyclerviewCategory.getAdapter() == null) {
            requestGoodTypeList();
        }
    }

    @Override
    public View createView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.fragment_good, container, false);
        init(root);
        return root;
    }

    private void init(View root) {
        show = getArguments().getInt("show");
        goodManager = GoodManager.getInstance(getContext());

        recyclerviewCategory = (RecyclerView) root.findViewById(R.id.recyclerview_category);
        recyclerviewTeams = (RecyclerView) root.findViewById(R.id.recyclerview_teams);

        mTeamsLayoutManager = new LinearLayoutManager(getActivity());
        mCategoryLayoutManager = new LinearLayoutManager(getActivity());
        recyclerviewCategory.setLayoutManager(mCategoryLayoutManager);
        recyclerviewTeams.setLayoutManager(mTeamsLayoutManager);

        recyclerviewCategory.addItemDecoration(new DividerItemDecoration(getActivity(),
                DividerItemDecoration.VERTICAL_LIST));
        recyclerviewTeams.addItemDecoration(new DividerItemDecoration(getActivity(),
                DividerItemDecoration.VERTICAL_LIST));


    }

    /**
     * 获取商品分类下的所有商品
     */
    private void requestGoodTypeList() {
        mDialogHelper.showLoadingProgressDialog();
        new GoodApi().listWithGoods(mUser.getShop().getStoreId(), mUser.getToken(), new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                T.ToastNetError();
                mDialogHelper.dismissProgressDialog();
            }

            @Override
            public void onResponse(String response, int id) {
                mDialogHelper.dismissProgressDialog();
                DataJson dataJson = new DataJson(response);
                if (dataJson.isSuccess()) {
                    try {
                        List<GoodsType> goodsTypes = new Gson().fromJson(dataJson.getData().toString(), new TypeToken<List<GoodsType>>() {
                        }.getType());
                        goodManager.addGoodData(goodsTypes);

                        if (mOnData != null) {
                            mOnData.onData();
                        }
                        initView();
                    } catch (Exception e) {
                    }
                } else {
                    T.ToastShort(dataJson.getMsg());
                }
            }
        });
    }

    /**
     * 删除切换
     *
     * @param isDelete
     */
    public void setDelete(boolean isDelete) {
        if (isDelete) {
            teamsAndHeaderAdapter.setOnItemClickListener(new TeamsAndHeaderAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(View view, int position) {
                    Good team = goodManager.getGoods().get(position);
                    team.setSelect(!team.isSelect());
                    GoodsType category = goodManager.getGoodsTypes().get(teamsAndHeaderAdapter.getSortType(position));
                    if (team.isSelect()) {
                        category.getSelectGoods().add(team);
                    } else {
                        category.getSelectGoods().remove(team);
                    }
                    categoryAdapter.notifyDataSetChanged();
                    teamsAndHeaderAdapter.notifyDataSetChanged();
                }
            });
        } else {
            List<GoodsType> categoryList = goodManager.getGoodsTypes();
            for (GoodsType goodsType : categoryList) {
                goodsType.getSelectGoods().clear();
                for (Good good : goodsType.getGoodsList()) {
                    good.setSelect(false);
                }
            }
            categoryAdapter.notifyDataSetChanged();
            teamsAndHeaderAdapter.setOnItemClickListener(new TeamsAndHeaderAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(View view, int position) {
                    startGoodDetailActivity(goodManager.getGoods().get(position).getId());
                }
            });
        }
        teamsAndHeaderAdapter.setDelete(isDelete);
        teamsAndHeaderAdapter.notifyDataSetChanged();
    }


    /**
     * 初始化视图
     */
    private void initView() {
        categoryAdapter = new CategoryAdapter(getActivity(), goodManager);
        categoryAdapter.setShowType(show);
        categoryAdapter.setOnItemClickListener(this);
        recyclerviewCategory.setAdapter(categoryAdapter);

        teamsAndHeaderAdapter = new TeamsAndHeaderAdapter(getActivity(), goodManager);
        teamsAndHeaderAdapter.setShowType(show);
        recyclerviewTeams.setAdapter(teamsAndHeaderAdapter);

        /**
         * 添加监听
         */
        goodManager.addOnChangeListener(categoryAdapter);
        goodManager.addOnChangeListener(teamsAndHeaderAdapter);
        // Add the sticky headers decoration,给球队添加标题
        final StickyRecyclerHeadersDecoration headersDecor = new StickyRecyclerHeadersDecoration(teamsAndHeaderAdapter);
        recyclerviewTeams.addItemDecoration(headersDecor);

        teamsAndHeaderAdapter.setOnItemClickListener(new TeamsAndHeaderAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                if (show == DELETE) {
                    startGoodDetailActivity(goodManager.getGoods().get(position).getId());
                }
            }
        });


        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            recyclerviewTeams.setOnScrollChangeListener(new View.OnScrollChangeListener() {
                @Override
                public void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
                    //第一个完全显示的item和最后一个item。
                    int firstVisibleItem = mTeamsLayoutManager.findFirstCompletelyVisibleItemPosition();
                    int lastVisibleItem = mTeamsLayoutManager.findLastVisibleItemPosition();
                    //此判断，避免左侧点击最后一个item无响应
                    if (lastVisibleItem != mTeamsLayoutManager.getItemCount() - 1) {
                        int sort = teamsAndHeaderAdapter.getSortType(firstVisibleItem);
                        changeSelected(sort);
                    } else {
                        changeSelected(categoryAdapter.getItemCount() - 1);
                    }
                    if (needMove) {
                        needMove = false;
                        //获取要置顶的项在当前屏幕的位置，mIndex是记录的要置顶项在RecyclerView中的位置
                        int n = movePosition - mTeamsLayoutManager.findFirstVisibleItemPosition();
                        if (0 <= n && n < recyclerviewTeams.getChildCount()) {
                            //获取要置顶的项顶部离RecyclerView顶部的距离
                            int top = recyclerviewTeams.getChildAt(n).getTop() - dip2px(getActivity(), 28);
                            //最后的移动
                            recyclerviewTeams.scrollBy(0, top);
                        }
                    }
                }
            });
        } else {
            recyclerviewTeams.setOnScrollListener(new RecyclerView.OnScrollListener() {
                @Override
                public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                    super.onScrolled(recyclerView, dx, dy);
                    //第一个完全显示的item和最后一个item。
                    int firstVisibleItem = mTeamsLayoutManager.findFirstCompletelyVisibleItemPosition();
                    int lastVisibleItem = mTeamsLayoutManager.findLastVisibleItemPosition();
                    //此判断，避免左侧点击最后一个item无响应
                    if (lastVisibleItem != mTeamsLayoutManager.getItemCount() - 1) {
                        int sort = teamsAndHeaderAdapter.getSortType(firstVisibleItem);
                        changeSelected(sort);
                    } else {
                        changeSelected(categoryAdapter.getItemCount() - 1);
                    }
                    if (needMove) {
                        needMove = false;
                        //获取要置顶的项在当前屏幕的位置，mIndex是记录的要置顶项在RecyclerView中的位置
                        int n = movePosition - mTeamsLayoutManager.findFirstVisibleItemPosition();
                        if (0 <= n && n < recyclerviewTeams.getChildCount()) {
                            //获取要置顶的项顶部离RecyclerView顶部的距离
                            int top = recyclerviewTeams.getChildAt(n).getTop() - dip2px(getActivity(), 28);
                            //最后的移动
                            recyclerviewTeams.scrollBy(0, top);
                        }
                    }
                }
            });
        }
    }

    private boolean needMove = false;
    private int movePosition;

    private void moveToPosition(int n) {
        //先从RecyclerView的LayoutManager中获取第一项和最后一项的Position
        int firstItem = mTeamsLayoutManager.findFirstVisibleItemPosition();
        int lastItem = mTeamsLayoutManager.findLastVisibleItemPosition();
        //然后区分情况
        if (n <= firstItem) {
            //当要置顶的项在当前显示的第一个项的前面时
            recyclerviewTeams.scrollToPosition(n);
        } else if (n <= lastItem) {
            //当要置顶的项已经在屏幕上显示时
            int top = recyclerviewTeams.getChildAt(n - firstItem).getTop();
            recyclerviewTeams.scrollBy(0, top - dip2px(getActivity(), 28));
        } else {
            //当要置顶的项在当前显示的最后一项的后面时
            recyclerviewTeams.scrollToPosition(n);
            movePosition = n;
            needMove = true;
        }
    }


    /**
     * 跳转商品详情界面
     *
     * @param goodId
     */
    private void startGoodDetailActivity(String goodId) {
        Intent intent = new Intent(getActivity(), GoodAddActivity.class);
        intent.putExtra("goodId", goodId);
        intent.putExtra("type", 1);
        startActivity(intent);
    }

    @Override
    public void onItemClick(int position) {
        changeSelected(position);
        moveToThisSortFirstItem(position);

    }

    private void moveToThisSortFirstItem(int position) {
        movePosition = 0;
        for (int i = 0; i < position; i++) {
            movePosition += goodManager.getGoodsTypes().get(i).getGoodsList().size();
        }
        moveToPosition(movePosition);
    }

    private void changeSelected(int position) {
        goodManager.getGoodsTypes().get(oldSelectedPosition).setSeleted(false);
        goodManager.getGoodsTypes().get(position).setSeleted(true);
        //增加左侧联动
        recyclerviewCategory.scrollToPosition(position);
        oldSelectedPosition = position;
        categoryAdapter.notifyDataSetChanged();
        this.typePosition = position;
    }

    /**
     * 分类选中位置
     * @return
     */
    private int typePosition;

    public int getTypePosition(){
        return typePosition;
    }

    /**
     * 根据手机分辨率从dp转成px
     *
     * @param context
     * @param dpValue
     * @return
     */
    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    public void deleteChange() {
        goodManager.delete();
        teamsAndHeaderAdapter.notifyDataSetChanged();
        categoryAdapter.notifyDataSetChanged();
    }
}
